using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Td.Additional.Log
{
    /// <summary>
    /// Class to hold events of current session in memory.
    /// </summary>
    public class MemoryLog : Log, INotifyLog
    {
        #region Properties

        /// <summary>
        /// Gets or sets the current session log.
        /// </summary>
        /// <value>The current session log.</value>
        public List<LogEntry> CurrentSessionLog { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="MemoryLog"/> class.
        /// </summary>
        public MemoryLog()
            : base()
        {
            LogLevel = LogLevel.Info;
            LogFullQualifiedMethodName = false;
            CurrentSessionLog = new List<LogEntry>();
        }

        #endregion

        #region Private helpers

        /// <summary>
        /// Writes the log entry.
        /// </summary>
        /// <param name="level">The level.</param>
        /// <param name="source">The source.</param>
        /// <param name="message">The message.</param>
        public override void WriteLogEntry(LogLevel level, string source, string message)
        {
            StackTrace stackTrace = new StackTrace();
            System.Reflection.MethodBase methodBase = null;
            int stackIndex = 2;

            while (stackTrace.FrameCount > stackIndex && typeof(ILog).IsAssignableFrom((methodBase = stackTrace.GetFrame(stackIndex).GetMethod()).ReflectedType))
                stackIndex++;

            string callingMethod = LogFullQualifiedMethodName ? String.Format("{0}.{1}", methodBase.ReflectedType.FullName, methodBase.Name) : methodBase.Name;

            LogEntry logEntry = new LogEntry();
            logEntry.TimeStamp = DateTime.Now;
            logEntry.Level = level;
            logEntry.Source = callingMethod;
            logEntry.Message = message;
            lock (CurrentSessionLog)
                CurrentSessionLog.Add(logEntry);
            OnNewEntry(this, new EventArgs<LogEntry>(logEntry));
        }

        #endregion

        #region Events

        /// <summary>
        /// Occurs when [new entry].
        /// </summary>
        public event EventHandler<EventArgs<LogEntry>> NewEntry;

        /// <summary>
        /// Called when [new entry].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The EventArgs&lt;LogEntry&gt; instance containing the event data.</param>
        protected virtual void OnNewEntry(Object sender, EventArgs<LogEntry> e)
        {
            EventHandler<EventArgs<LogEntry>> tempNewEntry = NewEntry;
            if (tempNewEntry != null)
                tempNewEntry(sender, e);
        }

        #endregion
    }
}